/*
 *  Copyright (C) 2015, Jhuster, All Rights Reserved
 *
 *  Author:  Jhuster(lujun.hust@gmail.com)
 *  
 *  https://github.com/Jhuster/JNote
 *  
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 */
package com.ksd1.notes.markdown;

import android.text.Editable;
import android.widget.EditText;
import android.widget.TextView.BufferType;

/**
 * 写md文件
 */
public class MDWriter {

    public static final String HEADER = "# ";
    public static final String HEADER2 = "## ";
    public static final String HEADER3 = "### ";
    public static final String CENTER_LEFT = "{";
    public static final String CENTER_RIGHT = "}";
    public static final String BOLD = "**";
    public static final String LIST = "- ";
    public static final String QUOTE = "> ";

    private class Position {
        int start;
        int end;

        public Position(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }

    private final EditText mEditText;//在此EditText上编辑


    /**
     * 传递一个edittext进行初始化
     * @param edittext 初始化editText
     */
    public MDWriter(EditText edittext) {
        mEditText = edittext;
    }


    /**
     * 设置EditText的内容
     * @param content 内容
     */
    public void setContent(String content) {
        mEditText.setText(content, BufferType.EDITABLE);
    }


    /**
     * 在EditText光标所在行添加 #
     * @return true or false
     */
    public boolean setAsHeader() {
        String content = mEditText.getText().toString();
        Position position = getCurrentLinePosition(content);

        //如果前面已经是3级标题了，就不再添加
        if (content.substring(position.start, position.end).startsWith(HEADER3)) {
            return false;
        }

        //如果content不是以#号开头
        if (!content.substring(position.start, position.end).startsWith("#")) {
            insert(position.start, " ");
        }
        insert(position.start, "#");
        return true;
    }

    /**
     * 在EditText光标所在行添加{}
     * @return true or false
     */
    public boolean setAsCenter() {
        String content = mEditText.getText().toString();
        Position position = getCurrentLinePosition(content);
        if (content.substring(position.start, position.end).startsWith(CENTER_LEFT)) {
            return false;
        }
        insert(position.start, CENTER_LEFT);
        insert(position.end + 1, CENTER_RIGHT);
        return true;
    }

    /**
     * 添加**
     * @return true or false
     */
    public boolean setAsBold() {
        insert(getCurrentPosition(), BOLD);
        return true;
    }

    /**
     * 在EditText光标所在行添加 -
     * @return true or false
     */
    public boolean setAsList() {
        String content = mEditText.getText().toString();
        Position position = getCurrentLinePosition(content);
        if (content.substring(position.start, position.end).startsWith(LIST)) {
            return false;
        }
        insert(position.start, LIST);
        return true;
    }

    /**
     * 在EditText光标所在行添加 >
     * @return true or false
     */
    public boolean setAsQuote() {
        String content = mEditText.getText().toString();
        Position position = getCurrentLinePosition(content);
        if (content.substring(position.start, position.end).startsWith(QUOTE)) {
            return false;
        }
        insert(position.start, QUOTE);
        return true;
    }

    /**
     * @return 获取显示的文章标题（开头的第一句）
     */
    public String getTitle() {
        String content = mEditText.getText().toString();
        if ("".equals(content)) {
            return "";
        }
        int end = content.indexOf("\n");
        return content.substring(0, end == -1 ? content.length() : end);
    }

    public String getContent() {
        return mEditText.getText().toString();
    }


    /**
     * @param content 当前EditText的内容
     * @return 光标所在位置
     */
    protected Position getCurrentLinePosition(String content) {
        int index = 0;
        if ("".equals(content)) {
            return new Position(0, 0);
        }
        Position position = new Position(-1, -1);
        //Find the line header "\n"         
        index = getCurrentPosition();//行头
        while (index > 1 && content.charAt(index - 1) != '\n') {
            index--;
        }
        position.start = index == 1 ? 0 : index;//第一行


        index = getCurrentPosition();
        while (index < content.length() && content.charAt(index) != '\n') {
            index++;
        }
        position.end = index;//行尾
        return position;

        /*
        example:
            hello\n
            wor\n
            ld
            如果光标在第一行  返回：1 6
        */
    }


    /**
     * @return 光标前面的字符数量（包括\n  空格）
     */
    protected int getCurrentPosition() {
        return mEditText.getSelectionStart();
    }


    /**
     * 如果越界，追加到末尾
     * @param index 位置
     * @param text  文本
     */
    protected void insert(int index, String text) {
        Editable editor = mEditText.getEditableText();
        if (index < 0 || index >= editor.length()) {
            editor.append(text);
        } else {
            editor.insert(index, text);
        }
    }
}
